package com.wt.test;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @description
 * @author: wangtao
 * @date:15:56 2019/6/14
 * @email:taow02@jumei.com
 */
public class UserMain {
	public static void main(String[] args) throws MalformedURLException {
		NetworkClassLoader loader = new NetworkClassLoader(
				new URL[]{new URL("file:///D:\\minepro\\custom_class_loader\\lib\\myapp.jar")});
//		NetworkClassLoader loader = new NetworkClassLoader(
//				new URL[]{new URL("file:///D:\\minepro\\custom_class_loader\\lib\\myapp.jar")},null);
		Thread.currentThread().setContextClassLoader(loader);
		//用forname和loadclass都一样
		//		Class<?> aClass = Class.forName("com.wt.demo.User", true, loader);

		com.wt.test.Person p = new com.wt.test.Person();
		System.out.println(p.getClass().getClassLoader());

		//如果上面用第二个loader，指定了父loader为null之后，加载不了UserInterface，
		//上面的Person是由Appclassoader加载的，我们的UserInterface也会由AppclassLoader加载
		//因为我们的loader加载了com.wt.demo.User这个类，所以，UserInterface也必须由loader开始加载，
		//当然如果没有破坏双亲委托机制的话，他会先去委托AppClassloader加载UserInterface，
		//因为我们设置了parent为null，所以这里加载不到，我们的loader不会加载当前classpath的类
		try {
			Class<?> aClass = loader.loadClass("com.wt.demo.User");
			com.wt.test.UserInterface o = (com.wt.test.UserInterface) aClass.newInstance();
			System.out.println("userInterface.hello()----->"+o.hello("222"));
			System.out.println(o+"-------"+o.getClass().getClassLoader());
			System.out.println(aClass.getMethod("hello", String.class).invoke(o, "wt"));
		}catch (Throwable e){
			System.out.println("load UsrInterface fail   "+e.getMessage());
		}

		//看appClassLoader加载UserInterface
//		UserInterface u=new UserInterface() {
//			@Override
//			public String hello(String a) {
//				return null;
//			}
//		};

//		System.out.println("apploader--->"+u.getClass().getClassLoader());

		Thread thread = new Thread(() -> {
			Person ip = new Person();
			System.out.println("t1:" + ip.getClass().getClassLoader());
		});
		Thread thread2 = new Thread(() -> {
			Person op = new Person();
			System.out.println("t2:" + op.getClass().getClassLoader());
		});
		thread.setContextClassLoader(loader);
		thread.start();
		thread2.start();
	}
}
